package com.baseweb.webadmin.controller.admin;

import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.AdPositionType;
import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.ChannelType;
import com.baseweb.webadmin.core.constants.OrderStatus;
import com.baseweb.webadmin.core.model.bvo.*;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.CitiesUtil;
import com.baseweb.webadmin.core.util.CommonUtil;
import com.baseweb.webadmin.core.util.RequestPage;
import com.baseweb.webadmin.service.ContentService;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangs on 2017/6/18.
 */
@Controller
@RequestMapping("/by")
public class MerchantsController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/compereHtml")
    public String compereHtml() {
        return "compere_List.html";
    }

    @RequestMapping(value = "/merchants", method = RequestMethod.GET, produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String merchants(@RequestParam(value = "page", defaultValue = "1") Integer page,
                            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                            @RequestParam(value = "user_id", required = false) Integer user_id,
                            @RequestParam(value = "product_type", required = false) Integer product_type,
                            @RequestParam(value = "parent_id", required = false) Integer parent_id,
                            @RequestParam(value = "channel_id", required = false) Integer channel_id,
                            @RequestParam(value = "key_id", required = false) Integer key_id,
                            @RequestParam(value = "position_id", required = false) Integer position_id,
                            @RequestParam(value = "sort", required = false) String sort,
                            @RequestParam(value = "style_type", required = false) String style_type,
                            @RequestParam(value = "price", required = false) String price,
                            @RequestParam(value = "keyword", required = false) String keyword,
                            @RequestParam(value = "city", required = false) String city,
                            @RequestParam(value = "area", required = false) String area,
                            @RequestParam(value = "conv_date", required = false) String convDate,
                            @RequestParam(value = "orderBy", required = false) String orderBy,
                            HttpServletRequest request,
                            Model model) {
        System.out.println("MerchantsController -> merchants");
        HttpSession session = request.getSession();

        if (StringUtils.isBlank(city)){
            city = (String) session.getAttribute("current_city");
            if (StringUtils.isBlank(city)){
                city = "成都市";
                session.setAttribute("current_city", city);
            }
        }

        List<UserInfoDetailBvo> list = new ArrayList<UserInfoDetailBvo>();
        List<User> bizList = userService.selectBizUserListByPage(product_type,key_id,channel_id,sort,style_type,price,keyword,(page-1)*pageSize, pageSize,
                BaseState.NORMAL.getCode(),city, area, orderBy);
        int total = userService.selectBizUserListCount(product_type,key_id,channel_id,sort,style_type,price,keyword,
                BaseState.NORMAL.getCode(),city, area);

        if (bizList != null && bizList.size() > 0){
            String isContinue = "";
            for (User current : bizList){
                if (current.getId() == 1) { // 管理员（排除，在商家列表不显示）
                    continue;
                }
                // 根据商家ID获取所有报价信息
                List<ByUserBizProductBvo> productBvos = userService.selectProductVoListByPage(current.getId(), null, null, null, null, null, 1, null, null, null, null, null,
                        0, 99);
                BigDecimal mix = null;
                if (productBvos != null && productBvos.size() > 0) {
                    for (ByUserBizProductBvo bvo : productBvos) {
                        BigDecimal cp = bvo.getCurrentPrice();
                        if (mix == null || cp.compareTo(mix) == -1) { // -1 小于；0 等于；1 大于
                            mix = cp;
                        }
                    }
                }
                current.setBizPrice(mix);
                isContinue = "0";
                if (convDate != null && !"".equals(convDate)) {
                    String[] dates = convDate.split("-");
                    Map<String, String> scheduleData = userOrderService.getUserScheduleListView(current.getId(), Integer.valueOf(dates[0]),
                            Integer.valueOf(dates[1]), Integer.valueOf(dates[2]));
                    for (Map.Entry<String, String> entry : scheduleData.entrySet()) {
                        if (!"greyClass".equals(entry.getValue())) {
                            isContinue = "1";
                            break;
                        }
                    }
                }
                if (convDate == null || "".equals(convDate) || isContinue.equals("1")) {
                    UserInfoDetailBvo bvo = UserInfoDetailBvo.copyFrom(current, null, null, null);

                    // 商家资质
                    List<ByUserBizAuth> authList = userService.findUserBizAuthByUserId(current.getId());
                    bvo.setAuthList(authList);
                    list.add(bvo);
                }
            }
        }

        model.addAttribute("bizList", list);
        model.addAttribute("total", total);

        int totalPage = total/pageSize;
        int tmpDiv = total%pageSize;
        if (tmpDiv > 0){
            totalPage +=1;
        }
        model.addAttribute("totalPage", totalPage);

        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", pageSize);

        model.addAttribute("parent_id", parent_id);
        model.addAttribute("channel_id", channel_id);
        model.addAttribute("position_id", position_id);
        model.addAttribute("style_type", style_type);

        model.addAttribute("price", price);
        model.addAttribute("keyword", keyword);

        model.addAttribute("city", city);
        model.addAttribute("area", area);

        if (StringUtils.isNotBlank(city)) {
            session.setAttribute("area_list", CitiesUtil.getAreasListByCityName(city));
        }

        Gson gson = new Gson();
        String results = gson.toJson(model);
        return results;
    }

    @RequestMapping(value = "/detailHtml")
    public String biz_index() {
        return "Details.html";
    }

    @RequestMapping(value = "/detailData", method = RequestMethod.GET, produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String detailData(@RequestParam(value = "user_id") Integer user_id,
                             @RequestParam(value = "city",required = false) String city,
                             Model model) {
        System.out.println("MerchantsController -> detailData");
        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        User user = userService.selectUserById(user_id);
        model.addAttribute("user", user);

        if (user.getBizViewCount() != null && user.getBizViewCount() > 0){
            user.setBizViewCount(user.getBizViewCount() + 1);
            userService.updateUser(user);
        }else{
            user.setBizViewCount(1);
            userService.updateUser(user);
        }

        User currentUser = getCurrentUser();

        if (currentUser != null && user != null && (currentUser.getId().intValue() == user.getId().intValue())) {
            model.addAttribute("is_me", "");
        }

//        ByChannel channel = contentService.findChannel(user.getBizWorkType());
        Role role = roleService.findRoleByUserIdType(user_id,"2");
//        channel.setName(role.getRoleName());
        Map<String,String> map = new HashMap<>();
        map.put("name",role.getRoleName());
        model.addAttribute("channel", map);

        // 商家资质
        List<ByUserBizAuth> authList = userService.findUserBizAuthByUserId(user_id);
//        List<ByUserBizAuth> authList = userService.selectBizVerifyListByPage(user.getId(), null, null, 0,5, BaseState.NORMAL.getCode());
        model.addAttribute("authList", authList);

        List<ByUserBizProduct> productList = userService.selectProductListByPage(user.getId(), null, null, 0, 20,null,null,null,null, BaseState.NORMAL.getCode());
        model.addAttribute("productList", productList);

        ByUserExampleBvo exampleBvo = new ByUserExampleBvo();
        exampleBvo.setDescn("detail");
        UserInfoBvo userInfoBvo = new UserInfoBvo();//商家详情中作品只能查询上架后的数据
        userInfoBvo.setId(user_id);
        exampleBvo.setUserInfoBvo(userInfoBvo);
        RequestPage requestPage = new RequestPage();
        requestPage.setCurPage(1);
        requestPage.setPageSize(8);
        List<ByUserExampleBvo> exampleList = userService.selectExampleBvoListByPage(exampleBvo,requestPage);
//        List<ByUserExample> exampleList = userService.selectExampleListByPage(user.getId(),BaseState.NORMAL.getCode(), null, 0, 8);
        model.addAttribute("exampleList", exampleList);
        userInfoBvo.setId(null);
        userInfoBvo.setCity(city);
        exampleBvo.setDescn("case");
        exampleBvo.setUserInfoBvo(userInfoBvo);
        requestPage.setPageSize(10);
//        List<ByAd> youLikeList = contentService.findAllByAdByPositionId(AdPositionType.INDEX_YOULIKEBOTTOM.getCode(),10,"");
        List<ByUserExampleBvo> youLikeList = userService.selectExampleBvoListByPage(exampleBvo,requestPage);
        model.addAttribute("youLikeListB", youLikeList);

        //开通城市
        Map<String, List<String>> openCitiesMap = new HashMap<String, List<String>>();
        List<ByOpenCity> opencities = userService.findUserCityByUserId(user.getId());
        if (opencities !=null && opencities.size() > 0) {

            for (ByOpenCity current: opencities) {
                if (openCitiesMap.containsKey(current.getProvince())) {
                    openCitiesMap.get(current.getProvince()).add(current.getCity());
                } else {
                    List<String> list = new ArrayList<>();
                    list.add(current.getCity());
                    openCitiesMap.put(current.getProvince(), list);
                }
            }

        }
        model.addAttribute("openCitiesMap", openCitiesMap);

        // 订单总数
        Integer orderCount = userOrderService.selectOrderListByBizUserCount(null,null,null, user_id, OrderStatus.BIZ_RECEIVE_ORDER.getCode(), null,null,null, null,null);
        model.addAttribute("orderCount", orderCount);

        // 评价总数
        Integer commentsCount = userOrderService.countOrderDiscuss(user_id);

        ByUserOrder order = new ByUserOrder();
        order.setBizUserId(user_id);
        List<ByUserOrderEvaluatvo> evaList = userOrderService.selectOrderListByBizUserOfEvaluation(order, 0, 5);
        Map<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentList", evaList);
        commentMap.put("commentTotal", commentsCount);
        model.addAttribute("comments", commentMap);

        Map<String, String> scheduleData = userOrderService.getUserScheduleListView(user_id, 0, 0);

        if (scheduleData != null && scheduleData.keySet().size() > 0) {
            try {
                model.addAttribute("scheduleData", new ObjectMapper().writeValueAsString(scheduleData));
            } catch (IOException e) {
                model.addAttribute("scheduleData", "");
                e.printStackTrace();
            }
        }else{
            model.addAttribute("scheduleData", "");
        }

        //信誉
        Role creditRole = roleService.findRoleByUserIdType(user_id, "4");
        if (creditRole != null) {
            model.addAttribute("creditData", creditRole.getRemark());
        }

        List<ByUserRecommendBvo> list = new ArrayList<ByUserRecommendBvo>();
        // 推荐团队
        List<ByUserRecommend> byUserRecommends = userService.findAllRecommendByUserIdPage(user_id, 0, 6);

        if (byUserRecommends != null && byUserRecommends.size() > 0){
            for (ByUserRecommend current : byUserRecommends){
                User recommendUser = userService.selectUserById(current.getRecommendId());
                if (recommendUser != null) {
                    UserInfoBvo recommendUserBvo = UserInfoBvo.copyFrom(recommendUser, null, contentService.findChannel(recommendUser.getBizWorkType()));
                    // 根据商家ID获取所有报价信息
                    List<ByUserBizProductBvo> productBvos = userService.selectProductVoListByPage(recommendUser.getId(), null, null, null, null, null, 1, null, null, null, null, null,
                            0, 99);
                    BigDecimal mix = null;
                    if (productBvos != null && productBvos.size() > 0) {
                        for (ByUserBizProductBvo bvo : productBvos) {
                            BigDecimal cp = bvo.getCurrentPrice();
                            if (mix == null || cp.compareTo(mix) == -1) { // -1 小于；0 等于；1 大于
                                mix = cp;
                            }
                        }
                    }
                    recommendUserBvo.setBizPrice(mix);
                    list.add(ByUserRecommendBvo.copyFrom(current, userService.selectUserById(current.getUserId()),
                            recommendUserBvo, userService.findExample(current.getExampleId())));
                }
            }
        }
        model.addAttribute("recommendUsers", list);

        //关注度
        model.addAttribute("follow", userService.countFollowByFollowUserId(user_id));

        Gson gson = new Gson();
        String results = gson.toJson(model);

        return results;
    }

    @RequestMapping(value = "/adHtml")
    public String adHtml() {
        return "case_List.html";
    }

    @RequestMapping(value = "/adList", method = RequestMethod.GET, produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String ad_list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "pageSize", defaultValue = "24") Integer pageSize,
                          @RequestParam(value = "parent_id", required = true) Integer parent_id,
                          @RequestParam(value = "position_id", required = true) Integer position_id,
                          @RequestParam(value = "user_id", required = false) Integer user_id,
                          @RequestParam(value = "case_type", required = false) String case_type,
                          @RequestParam(value = "case_environment", required = false) String case_environment,
                          @RequestParam(value = "case_detail", required = false) String case_detail,
                          @RequestParam(value = "orderDesn", required = false) String orderDesn,
                          @RequestParam(value = "city", required = false) String city,
                          @RequestParam(value = "flag", required = true) String flag,//case  表示婚礼案例  detail表示商家详情中作品列表，需同时传商家ID user_id
                          Model model) {

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        model.addAttribute("topList", topList);

        model.addAttribute("positionName", AdPositionType.getNameByCode(position_id).getName());

        ByAd parent = contentService.findAd(parent_id);
        if (parent != null) {
            model.addAttribute("columnName", parent.getName());
        }

        if (position_id == AdPositionType.INDEX_CEHUA.getCode()
                || position_id == AdPositionType.INDEX_ZHUCHI.getCode()
                || position_id == AdPositionType.INDEX_SHEYINGSHI.getCode()
                || position_id == AdPositionType.INDEX_HUAZHUANGSHI.getCode()
                || position_id == AdPositionType.INDEX_SHEXIANGSHI.getCode() ){
            model.addAttribute("is_show", true);
        }

        int total = 0;
        //List<ByAd> list = contentService.selectAdListByPage(position_id, parent_id, BaseState.NORMAL.getCode(), (page - 1) * pageSize, pageSize);
        //total = contentService.selectAdListCount(position_id, parent_id, BaseState.NORMAL.getCode());
        String orderCol = "", orderStyle = "";
        if (orderDesn != null && !orderDesn.equals("")) {
            String[] orderArr = orderDesn.split("-");
            if (orderArr != null && orderArr.length > 1) {
                orderCol = orderArr[0];
                orderStyle = orderArr[1];
            } else if (orderArr != null && orderArr.length == 1) {
                orderCol = orderArr[0];
            } else {
                orderCol = orderDesn;
            }
        }
        ByUserExampleBvo exampleBvo = new ByUserExampleBvo();
        if("价格".equals(orderCol)){
            exampleBvo.setOrderDesn("cast(case_detail as signed INTEGER)" + " " + orderStyle);
        }else if("好评率".equals(orderCol)){
            exampleBvo.setOrderDesn("goodD" + " " + orderStyle);
        }else if("猜你喜欢".equals(orderCol)){
            exampleBvo.setOrderDesn("create_time" + " desc");
        }else if("浏览量".equals(orderCol)) {
            exampleBvo.setOrderDesn("view_count" + " " + orderStyle);
        }
        UserInfoBvo userInfoBvo = new UserInfoBvo();
        userInfoBvo.setCity(city);
        exampleBvo.setDescn(flag);
        if("detail".equals(flag)){//商家详情中作品只能查询上架后的数据

            userInfoBvo.setId(user_id);
        }
        exampleBvo.setUserInfoBvo(userInfoBvo);
        RequestPage requestPage = new RequestPage();
        requestPage.setCurPage(page);
        requestPage.setPageSize(pageSize);
        if (case_type != null && !"".equals(case_type)) {
            exampleBvo.setCaseType(case_type);
        }
        if (case_environment != null && !"".equals(case_environment)) {
            exampleBvo.setCaseEnvironment(case_environment);
        }
        if (case_detail != null && !"".equals(case_detail)) {
            exampleBvo.setCaseDetail(case_detail);
        }
        List<ByUserExampleBvo> list = userService.selectExampleBvoListByPage(exampleBvo,requestPage);
        total = requestPage.getTotal();
        model.addAttribute("bizList", list);
        model.addAttribute("total", total);

        int totalPage = total/pageSize;
        int tmpDiv = total%pageSize;
        if (tmpDiv > 0){
            totalPage +=1;
        }
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("parent_id", parent_id);
        model.addAttribute("position_id", position_id);

        Gson gson = new Gson();
        String results = gson.toJson(model);
        System.out.println("results: " + results);
        return results;
    }

    /**
     * 获取商家档期信息
     * @param user_id 商家ID
     * @param model 返回值模型
     * @return 商家档期信息json字符串
     */
    @RequestMapping(value = "/schedule", method = RequestMethod.GET, produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String schedule(@RequestParam(value = "user_id") Integer user_id,
                           HttpServletRequest request,
                           Model model) {
        if (user_id == 0) {
            user_id = Integer.valueOf(request.getSession().getAttribute("login_id").toString());
        }
        Map<String, String> scheduleData = userOrderService.getUserScheduleListView(user_id, 0, 0);

        if (scheduleData != null && scheduleData.keySet().size() > 0) {
            try {
                model.addAttribute("scheduleData", new ObjectMapper().writeValueAsString(scheduleData));
            } catch (IOException e) {
                model.addAttribute("scheduleData", "");
                e.printStackTrace();
            }
        }else{
            model.addAttribute("scheduleData", "");
        }

        Gson gson = new Gson();
        String results = gson.toJson(model);
        System.out.println("results: " + results);

        return results;
    }

    /**
     * 获取商家相关得评论信息列表
     * @param user_id 商家ID
     * @param page 当前页
     * @param pageSize 每页条数
     * @param model 返回模型
     * @return 返回json字符串
     */
    @RequestMapping(value = "/comments", method = RequestMethod.GET, produces = "text/json; charset=UTF-8")
    @ResponseBody
    public String comments(@RequestParam(value = "user_id") Integer user_id,
                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                           Model model) {

        Integer commentsCount = userOrderService.countOrderDiscuss(user_id);

        ByUserOrder order = new ByUserOrder();
        order.setBizUserId(user_id);
        List<ByUserOrderEvaluatvo> evaList = userOrderService.selectOrderListByBizUserOfEvaluation(order, 0, 5);
        Map<String, Object> commentMap = new HashMap<>();
        commentMap.put("commentList", evaList);
        commentMap.put("commentTotal", commentsCount);
        model.addAttribute("comments", commentMap);
        model.addAttribute("page", page);

        Gson gson = new Gson();
        String results = gson.toJson(model);
        System.out.println("results: " + results);

        return results;
    }

}